<template>
    <view class="chat-container">

        <view class="chat-container-in">

            <!-- <view class="header">
                <u-icon name="list" size="20" @click="showHistory=true"></u-icon>
                <text></text>
                <text>deepSeek</text>
                <text></text>
            </view> -->
            <!-- 主聊天区域 -->
            <view class="main-content">
                <!-- <view v-if="dialogueList"> -->
                <scroll-view v-if="dialogueList.length" scroll-y="true" class="chat-area" :scroll-top="scrollTop" @scroll="handleScroll"
                    @scrolltolowe="scrolltolower">
                    <view class="message-list">
                        <view v-for="(item, index) in dialogueList" :key="index">
                            <!-- 用户消息 -->
                            <view class="message-right">
                                <view class="message-bubble user">{{item.query}}</view>
                                <!-- <image class="avatar" src="../static/robot.png"></image> -->
                            </view>

                            <!-- AI回复 -->
                            <view class="message-left" v-if="item.answerThink">
                                <image class="avatar" src="../static/robot.png"></image>
                                <view class="message-bubble ai">
                                    <u-collapse :ref="'collapse'+index" :value='item.collapseValue' :border="false"
                                        @change="changeCollapse($event,index)">
                                        <u-collapse-item :title="item.answerText ? '已深度思考' : thinking" :name="'think'+index">
                                            <view class="think-content">{{item.answerThink}}</view>
                                        </u-collapse-item>
                                    </u-collapse>
                                    <view class="ai-content">{{item.answerText}}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </scroll-view>
                <!-- </view> -->
                <view v-else class="defaultBox">
                    <view>
                        <image src="../static/logo.jpg"></image>
                        <view class="titleBox">嗨！我是心诚办智能助手</view>
                        <view class="subtitleBox">我可以帮您搜索。答疑政务相关问题</view>
                    </view>
                </view>

            </view>
            <!-- 输入框区域 -->
            <view class="input-area">
                <!-- <view class="input-box"> -->
                <u--input v-model="sendValue" placeholder="输入您的问题" :confirm-type="'send'" @confirm="sendChat"
                    @keyboardheightchange="keyboardHeightChange"></u--input>
                <view class="send-btn" @click="sendChat">
                    <u-icon :name="loading ? 'close-circle' : 'arrow-upward'" size="18" color="#fff"></u-icon>
                </view>
                <!-- </view> -->
            </view>
        </view>

        <!-- 底部导航栏 -->
        <!-- <u-tabbar 
      :value="currentTab" 
      @change="tabChange"
      :fixed="true"
      :placeholder="true"
      :safeAreaInsetBottom="true"
    >
      <u-tabbar-item text="聊天" icon="chat"></u-tabbar-item>
      <u-tabbar-item text="历史" icon="list"></u-tabbar-item>
    </u-tabbar> -->

        <!-- 左侧历史记录面板 - 移动端改为底部标签栏 -->

        <u-popup :show="showHistory" mode="left" @close="showHistory=false">
            <view class="history-tabs">
                <view class="new-chat-btn" @click="openNewChat">
                    <u-icon name="plus" size="20"></u-icon>
                    <text>新聊天</text>
                </view>
                <scroll-view scroll-y class="chat-list">
                    <view v-for="(item, index) in historyList" :key="index" class="chat-item" :class="{'active': conversationId === item.id}"
                        @click="clickHistoryItem(item)">
                        <view class="chat-content">
                            <!-- <u-icon name="chat" size="18"></u-icon> -->
                            <text class="chat-name">{{item.name}}</text>
                        </view>
                        <u-icon name="trash" size="18" @click.stop="handleDelete(item)"></u-icon>
                    </view>
                </scroll-view>
            </view>
        </u-popup>
        <!-- 删除确认弹窗 -->
        <u-modal v-model="showDeleteModal" :content="'删除后，该对话将不可恢复。确认删除吗？'" show-cancel-button @confirm="confirmDelete"></u-modal>
    </view>
</template>

<script>
// import { fetchEventSource } from "@microsoft/fetch-event-source";
// import { getToken } from '@/utils/auth'
// import toolBox from "@/api/toolBox";
import { TextDecoder, TextEncoder } from 'text-encoding';
export default {
    data() {
        return {
            currentTab: 0,
            showHistory: false,
            showDeleteModal: false,
            deleteItem: null,
            inputText: '',
            loading: false,
            sendAnswer: {},
            controller: null,
            progressDone: false,
            progressTxt: '',
            sendValue: '',
            userInfoDetail: {},
            conversationId: '',
            dialogueList: [
            ],
            // dialogueList: [
            //     {
            //         answerText: ", reasoning您好！我是心诚办智能助手，请问您咨询哪些政务服务事项？我将为您提供准确指引。(๑˃̵ᴗ˂̵)و",
            //         answerThink: "好的，用户发来了“你好”，我需要用友好的方式回应，同时介绍自己是心诚办智能助手，并主动询问是否有问题需要帮助。根据任务要求，回答要简洁，保持友好，并引导用户提出问题。现在检查参考资料中是否有相关问候的答案，但看起来参考资料主要是针对具体政务服务的问题回复，没有直接的问候模板。因此，按照任务指示，使用标准问候语即可，不需要引用具体资料。确保不涉及文档名称或作者，保持礼貌和简洁。\nll), reasoningContent=",
            //         collapseValue: [
            //             "thin0"
            //         ],
            //         query: "你好"
            //     }
            // ],
            thinking: '思考中',
            thinkingTime: null,
            pushTextKey: 'answerThink',
            historyList: [{
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }, {
                name: 'adas啊实打实大萨达asd asd 萨达撒'
            }],
            scrollTop: 0,
            keyboardHeight: 0,
            taskId: '',
            messageList: '',
            isHighFollowing: true,
            chatAreaHeight: '',

        };
    },
    // computed: {
    //     userInfo() {
    //         return this.$store.state.user.userInfo;
    //     }
    // },
    // watch: {
    //     userInfo(newVal) {
    //         this.userInfoDetail = newVal || {};
    //     },
    //     dialogueList() {
    //         this.$nextTick(() => {
    //             this.scrollToBottom();
    //         });
    //     }
    // },
    onLoad() {

        // this.conversationsM();
        // uni.createSelectorQuery().in(this).select('.chat-area').boundingClientRect(rect => {
        //     this.chatAreaHeight = rect.height
        // }).exec()
        // uni.createSelectorQuery().in(this).select('.message-list').boundingClientRect(rect => {
        //     if (this.isHighFollowing) {
        //         this.messageListHeight = rect.height;
        //         this.scrollTop = this.messageListHeight;
        //     }
        // }).exec()
        // this.dialogueList.push(
        //     {
        //         query: '你好我是问题你好我是问题你好我是问题你好我是问题你好我是问题',
        //         answerThink: '思考过程思考过程思考过程思考过程思考过程思考过程思考过程思考过程',
        //         collapseValue: 'think0',
        //         answerText: '我是一个回答大大大'
        //     })

    },
    methods: {
        changeCollapse(event, index) {
            if (event[0].status == 'open') {
                this.dialogueList[index].collapseValue = ['think' + [index]]
            }
            if (event[0].status == 'close') {
                this.dialogueList[index].collapseValue = false

            }
            // console.log('closeCollapse', a);
            // console.log('closeCollapse', index);
        },
        openCollapse(index) {
            console.log('openCollapse', index);
        },
        tabChange(index) {
            this.currentTab = index;
            this.showHistory = index === 1;
        },
        openNewChat() {
            if (this.dialogueList.length > 0) {
                this.dialogueList = [];
                this.conversationId = '';
                this.taskId = '';
                if (this.thinkingTime) {
                    clearInterval(this.thinkingTime);
                }
                this.pushTextKey = 'answerThink';
                this.stopMessages();
            }
        },
        handleDelete(item) {
            this.deleteItem = item;
            this.showDeleteModal = true;
        },
        confirmDelete() {
            toolBox.deleteMessages(this.deleteItem.id).then(val => {
                if (val.code == 200) {
                    this.$u.toast('删除成功');
                    this.conversationsM();
                }
            });
        },
        clickHistoryItem(item) {
            toolBox.getMessagesItem(item.id).then(val => {
                if (val.code == 200) {
                    this.conversationId = item.id;
                    this.dialogueList = [];
                    let dataList = JSON.parse(val.msg).data;
                    for (var i in dataList) {
                        this.dialogueList.push({
                            query: dataList[i].query,
                            answerThink: dataList[i].answer.split('\n\n\n\n')[0],
                            answerText: dataList[i].answer.split('\n\n\n\n')[1],
                            collapseValue: []
                        });
                    }
                    this.currentTab = 0;
                    this.showHistory = false;
                }
            });
        },
        conversationsM() {
            toolBox.conversations().then(val => {
                if (val.code == 200) {
                    this.historyList = JSON.parse(val.msg).data || [];
                }
            });
        },
        setThinkingTime() {
            if (this.thinkingTime) {
                clearInterval(this.thinkingTime);
            }
            this.thinkingTime = setInterval(() => {
                if (this.thinking == '思考中.....') {
                    this.thinking = '思考中';
                }
                this.thinking = this.thinking + '.';
            }, 300);
        },
        stopMessages() {
            if (this.taskId) {
                toolBox.stopMessages(this.taskId).then(val => {
                    if (val.code == 200) {
                        this.taskId = '';
                        this.loading = false;
                        if (this.thinkingTime) {
                            clearInterval(this.thinkingTime);
                        }
                        this.pushTextKey = 'answerThink';
                        this.dialogueList[this.dialogueList.length - 1].answerText = '已停止生成......';
                        this.dialogueList[this.dialogueList.length - 1].collapseValue = [];
                    }
                });
            }
        },
        sendChat() {
            let that = this;

            this.isHighFollowing = true
            if (that.sendValue) {
                let requestTask = this.$asynApi.chatStream({
                    content: that.sendValue
                })
                let index = this.dialogueList ? this.dialogueList.length : 0
                that.dialogueList.push(
                    {
                        query: that.sendValue,
                        answerThink: '',
                        collapseValue: ['think' + [index]],
                        answerText: ''
                    })
                // requestTask.success((res)=>{
                //     console.log(res);
                //     console.log('success');
                // })
                that.sendValue = ''
                requestTask.onChunkReceived((res) => {
                    const decoder = new TextDecoder('utf-8');
                    const text1 = decoder.decode(res.data); // event.data 应是 Uint8Array 类型
                    // console.log(text1.split('\n\n'));
                    for (var i in text1.split('\n\n')) {
                        if (text1.split('\n\n')[i] && text1.split('\n\n')[i].includes('(') && text1.split('\n\n')[i].includes(')')) {
                            console.log(text1.split('\n\n')[i]);
                            // 思考
                            let ThinkstartIndex = text1.split('\n\n')[i].indexOf('reasoningContent=') + 'reasoningContent='.length; // 计算abc之后的起始索引
                            let ThinkendIndex = text1.split('\n\n')[i].indexOf(')'); // xyz的起始索引即为截取的结束索引
                            // console.log(ThinkstartIndex,ThinkendIndex);
                            if (ThinkstartIndex > 0 && ThinkendIndex > 0) {
                                let Think = text1.split('\n\n')[i].substring(ThinkstartIndex, ThinkendIndex)
                                if (Think && Think != 'null') {
                                    // console.log(Think);
                                    this.dialogueList[index].answerThink = this.dialogueList[index].answerThink + Think
                                }
                            }
                            // 结果
                            let TextstartIndex = text1.split('\n\n')[i].indexOf('generateAnswer=') + 'generateAnswer='.length; // 计算abc之后的起始索引
                            let TextendIndex = text1.split('\n\n')[i].indexOf(', reasoningContent'); // xyz的起始索引即为截取的结束索引
                            // console.log(TextstartIndex,TextendIndex);
                            if (TextstartIndex > 0 && TextendIndex > 0) {
                                let Text = text1.split('\n\n')[i].substring(TextstartIndex, TextendIndex)
                                if (Text && Text != 'null') {
                                    // console.log(Text);
                                    this.dialogueList[index].answerText = this.dialogueList[index].answerText + Text
                                }
                            }
                        }
                    }

                    uni.createSelectorQuery().in(this).select('.message-list').boundingClientRect(rect => {
                        if (this.isHighFollowing) {

                            this.messageListHeight = rect.height;
                            this.scrollTop = this.messageListHeight;
                        }
                    }).exec()
                    that.$nextTick(() => {
                        setTimeout(() => {
                            that.$refs['collapse' + index][0].init()
                        }, 2000)
                    })

                });
            }
        },
        scrollToBottom() {
            this.$nextTick(() => {
                this.scrollTop = 999999;
            });
        },
        handleScroll(e) {
            if (this.chatAreaHeight + e.detail.scrollTop + 40 < e.detail.scrollHeight) {
                this.isHighFollowing = false
            }
            else {
                this.isHighFollowing = true
            }
        },
        scrolltolower() {
            this.isHighFollowing = true
        },
        keyboardHeightChange(e) {
            this.keyboardHeight = e.detail.height;
            if (e.detail.height > 0) {
                this.scrollToBottom();
            }
        }
    },
    onUnload() {
        if (this.thinkingTime !== null) {
            clearInterval(this.thinkingTime);
            this.thinkingTime = null;
        }
    }
};
</script>

<style scoped lang="less">
.chat-container {
    // display: flex;
    // flex-direction: column;
    .chat-container-in {
        height: 100vh;
        background-color: #fff;
        position: relative;
        display: flex;
        flex-direction: column;
    }

    .history-tabs {
        width: 60vw;
        // position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        // background-color: #2b2a2c;
        z-index: 1000;
        padding: 20rpx;
        // display: flex;
        // flex-direction: column;

        .new-chat-btn {
            // background-color: #3e3e3e;
            border-radius: 10rpx;
            border: #5c5c5c solid 2rpx;
            padding: 20rpx;
            text-align: center;
            color: rgb(0, 0, 0);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20rpx;

            text {
                margin-left: 10rpx;
            }
        }

        .chat-list {
            flex: 1;
            overflow-y: scroll;
            height: calc(100vh - 150rpx);

            .chat-item {
                // background-color: #454849;
                border-radius: 10rpx;
                padding: 20rpx 20rpx 20rpx 0rpx;
                display: flex;
                justify-content: space-between;
                align-items: center;
                color: rgb(0, 0, 0);
                font-size: 28rpx;
                margin-bottom: 20rpx;

                &.active {
                    background-color: #b4b4b4 !important;
                    color: #000 !important;
                }

                .chat-content {
                    flex: 1;
                    display: flex;
                    align-items: center;
                    overflow: hidden;

                    .chat-name {
                        margin-left: 10rpx;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }
            }
        }
    }

    .header {
        padding: 20rpx;
        text-align: center;
        font-size: 30rpx;
        // font-weight: bold;
        border-bottom: 1rpx solid #e0e0e0;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        flex-shrink: 0;
        flex-grow: 0;
        text {
            min-width: 40rpx;
        }
    }
    .main-content {
        flex: 1;
        flex: 1 1 auto;
        // display: flex;
        // flex-direction: column;
        overflow: hidden;
        flex-grow: 1;
        // /deep/.u-collapse-item__content {
        //     height: fit-content !important;
        // }
        .defaultBox {
            display: flex;
            // flex-direction: column;
            text-align: center;
            justify-content: center;
            align-items: center;
            height: 100%;
            image {
                margin: 0 auto;
                width: 200rpx;
                height: 200rpx;
            }
            .titleBox {
                font-size: 34rpx;
                font-weight: 600;
                color: #000;
                margin-bottom: 20rpx;
            }
            .subtitleBox {
                font-size: 26rpx;
                color: #555;
            }
            // flex-direction: column;
        }
        /deep/.u-cell__body {
            padding: 8rpx 0 !important;
        }
        .chat-area {
            padding: 0 20rpx;
            background-color: #fff;
            width: calc(100% - 40rpx);
            height: 100%;

            .message-list {
                // padding: 120rpx;
            }

            .message-left,
            .message-right {
                display: flex;
                padding: 30rpx 0;

                .avatar {
                    width: 60rpx;
                    height: 80rpx;
                    // border-radius: 50%;
                }

                .message-bubble {
                    max-width: 70%;
                    padding: 20rpx;
                    border-radius: 20rpx;
                    font-size: 28rpx;
                    line-height: 1.5;
                }

                .user {
                    background-color: #a2cffc;
                        word-wrap:break-word;
                    // margin-right: 20rpx;
                }

                .ai {
                    background-color: #fff;
                    margin-left: 20rpx;
                    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

                    .think-content {
                        color: #666;
                        font-size: 26rpx;
                        word-wrap:break-word;
                    }

                    .ai-content {
                        margin-top: 20rpx;
                        word-wrap:break-word;
                    }
                }
                .ai::after {
                    content: "";
                    position: absolute;
                    width: 0;
                    height: 0;
                    left: 50%;
                    bottom: 100%;
                    margin-left: -10px;
                    border-width: 10px;
                    border-style: solid;
                    border-color: transparent transparent #f0f0f0 transparent;
                    border-bottom-color: rgb(255, 0, 0);
                }
            }

            .message-left {
                justify-content: flex-start;
            }

            .message-right {
                justify-content: flex-end;
            }
        }
    }
    .input-area {
        padding: 20rpx 20rpx 40rpx 20rpx;
        background-color: #fff;
        // border-top: 1rpx solid #e0e0e0;
        // position: fixed;
        bottom: 0;
        width: calc(100% - 40rpx);
        flex-shrink: 0;
        // flex-grow: 0;
        margin-top: 20rpx;

        // .input-box {
        position: relative;

        /deep/ .u-input {
            padding-right: 80rpx !important;

            background-color: #f5f5f5 !important;
            border: none !important;
            border-radius: 100rpx !important;
        }

        .send-btn {
            position: absolute;
            right: 30rpx;
            bottom: 50rpx;
            z-index: 10;
            font-weight: 600;
            padding: 10rpx;
            background-color: #9fbff8;
            border-radius: 50%;
        }
        // }
    }
}
</style>